<?php
/**
 * Created by PhpStorm.
 * User: matengfei
 * Date: 15/8/22
 * Time: 下午10:02
 */

header("Content-Type:text/html;Charset=utf-8");  // 解决乱码问题

require_once 'snoopy.php';

$baidu_api_key = "sgPAKYLc5YZsgW0G4YwQ8ico";


//echo "hello";

$word = $_GET['word'];
$word_content = urlencode($word);


$snoopy = new Snoopy();
$url = "http://openapi.baidu.com/public/2.0/bmt/translate" . '?client_id=' . $baidu_api_key . "&from=auto&to=auto&q=" . $word_content;
//echo $url;

$result = $snoopy->fetchtext($url);
if ($result) {
    //echo $snoopy->results;

    $raw_result = $snoopy->results;
    $decode_content = json_decode($snoopy->results);
    $result_decode = $decode_content->{'trans_result'};
    $translate = ($result_decode[0]->{'dst'});

    // 存放至数据库
    $con = mysql_connect("localhost:3306", "root", "root");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }

    mysql_query('set names utf8');  //解决乱码

    mysql_select_db("collectword", $con);

    /*
    $result = mysql_query("select * from t_word", $con);
    if(!$result){
       $sql = "CREATE TABLE t_word
       (
       raw_word varchar(256),
       t_explain varchar(256),
       t_add_time int
       )";
       mysql_query($sql,$con); // 建表
    }
    */


    date_default_timezone_set("Asia/Shanghai");
    $timenow = time();
    $timenow_str = date('Y-m-d H:i:s');
    $result = mysql_query("INSERT INTO t_word (raw_word, raw_explain, raw_result, add_time, add_time_str) VALUES ('$word', '$translate', '$raw_result', '$timenow', '$timenow_str')");
    //mysql_query("INSERT INTO t_word (raw_word) VALUES ('123')");
    mysql_close($con);

    echo $raw_result;


}



